package huanzhao.erp.util;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class AESUtil {
    private static final String ALGORITHM = "AES/CBC/PKCS5Padding";
    public static final String KEY = "Ci5@J9b9NHSKIfk9"; // 16 bytes key
    public static final String IV = "4T5Pbf94g8!9w%yN";  // 16 bytes IV

    /**
     * 加密字符串
     *
     * @return String
     * 2024/10/4 21:55:40
     */
    public static String encrypt(String text) throws Exception {
        return encrypt(text, KEY, IV);
    }

    /**
     * 解密字符串
     *
     * @return String
     * 2024/10/4 21:55:55
     */
    public static String decrypt(String text) throws Exception {
        return decrypt(text, KEY, IV);
    }

    /**
     * 使用特定的KEY和IV加密字符串
     *
     * @return String
     * 2024/10/4 21:56:42
     */
    public static String encrypt(String text, String KEY, String IV) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(StandardCharsets.UTF_8), "AES");
        IvParameterSpec ivSpec = new IvParameterSpec(IV.getBytes(StandardCharsets.UTF_8));
        cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
        byte[] encrypted = cipher.doFinal(text.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encrypted);
    }

    /**
     * 使用特定的KEY和IV解密字符串
     *
     * @return String
     * 2024/10/4 21:56:58
     */
    public static String decrypt(String text, String KEY, String IV) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(StandardCharsets.UTF_8), "AES");
        IvParameterSpec ivSpec = new IvParameterSpec(IV.getBytes(StandardCharsets.UTF_8));
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
        byte[] decodedBytes = Base64.getDecoder().decode(text);
        byte[] decrypted = cipher.doFinal(decodedBytes);
        return new String(decrypted, StandardCharsets.UTF_8);
    }
}

